import {Component, OnInit} from '@angular/core';
import {User} from "../user";
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {UsersService} from "../users.service";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {Validators, FormGroup, FormBuilder} from "@angular/forms";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";
import {TreeUtil} from "../../../../util/tree-util";
import {Subject,ReplaySubject} from "rxjs";
import {LogUtil} from "../../../../util/log-util";

declare var $;

@Component({
  selector: 'app-user-update',
  templateUrl: './user-update.component.html'
})
export class UserUpdateComponent implements OnInit {


  user: User;

  regionSubject : Subject<string> = new ReplaySubject();

  regionId :string;

  orgId :string;

  depId :string;

  userForm: FormGroup;

  isClick:boolean =true;

  isOrgClick:boolean =true;

  userType;


  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private logUtil: LogUtil,
    private treeUtil: TreeUtil,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService,
    private responseUtil: ResponseUtil,
    private usersService: UsersService
  ) {
    this.initObject();
  }

  ngOnInit() {
    //初始化面包屑
    this.pushPage();
    //初始化行政区划
    this.initRegionTree();
    this.initEnvAndGovTree();

    //初始化修改表单
    this.initUserFormUpdate();

    this.getUserType();
  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("用户系统", "");
    this.pageSubject.pushPage("用户管理", "修改", path);
  }

  /**
   *  初始化修改页面
   * @param userId
   */
  initUserFormUpdate() {
    //获取路径参数
    let userId = this.route.snapshot.params["userId"];
    if (!!userId) {
      this.usersService.getUserById(userId).subscribe(
        result => this.responseUtil.success(result, this.processGetResult),
        message => this.responseUtil.error(message)
      );
    }
  }

  /**
   * id查询成功后调用
   * @param json
   */
  private processGetResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.user = result.data;
      this.logUtil.debug(JSON.stringify(result.data));
      this.userForm.patchValue(this.user);
      this.user.regionName = "";
      this.user.orgName = "";
      this.user.depName = "";
      this.orgId = result.data.orgId;
      this.depId = result.data.depId;
      this.regionSubject.next(result.data.regionId);
      this.regionSubject.complete();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 保存修改信息
   */
  updataUserInfo() {
    this.user = this.userForm.value;
    this.usersService.updateUser(this.user).subscribe(
      result => this.responseUtil.success(result, this.processUpdateResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 修改成功后调用
   * @param json
   */
  private processUpdateResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message, () => this.cancelcustomerUpdate());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 取消修改
   */
  cancelcustomerUpdate() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.user = new User("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
    this.buildForm();
  }


  /**
   * 构造表单
   */
  buildForm(): void {
    this.userForm = this.fb.group({
      'userId': [this.user.userId],
      'name': [this.user.name, [
        Validators.required,
        Validators.maxLength(10)
      ]],
      'regionId': [this.user.regionId],
      'regionName': [this.user.regionName],
      'orgId': [this.user.orgId],
      'orgName': [this.user.orgName],
      'depId': [this.user.depId],
      'depName': [this.user.depName],
      'phone': [this.user.phone, [
        Validators.maxLength(14),
        // Validators.pattern(/^((0\d{2,3}-\d{7,8})|(1[3584]\d{9}))$/)
        Validators.pattern(/^(((13[0-9]{1})|(15[0-9]{1})|18[0-9]{1})+\d{8})|((((\d{3,4})-))(\d{7,9}))$/)
      ]],
      'type': [this.user.type],
      'duty': [this.user.duty, [
        Validators.maxLength(15),
      ]]
    });

    this.userForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }


  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.userForm) {
      return;
    }
    const form = this.userForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'name': '',
    'phone': '',
    'duty': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'name': {
      'required': '用户不能为空',
      'maxlength': '长度不能超过10',
    },
    'phone': {
      'maxlength': '长度不能超过14位',
      'pattern': '格式不正确'
    },
    'duty': {
      'maxlength': '长度不能超过15位'
    }
  };

  /**
   * 获取行政区划树
   */
  initRegionTree() {
    this.usersService.getRetrieveRegionsTree().subscribe(
      result => this.responseUtil.success(result, this.processRegionsTreeResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 对行政区划树结果处理
   * @param result
   */
  private processRegionsTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.regioCodezTree(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   *  行政区划树点击事件处理
   */
  private regioCodezTree(datasTree) {
    let datas = datasTree;
    // 新增中的树
    let userUpdateZtreeSetting = {
      view: {
         fontCss: this.setFontCss_ztree //设置字体颜色
      },
      callback: {
        onClick: this.userUpdateZtreeClick
      }
    };
    let treeObj = $.fn.zTree.init($("#user_update_orgTree"), userUpdateZtreeSetting, datas);

    this.regionSubject.asObservable().subscribe(
      regionId => {
        if (!!regionId) {
          var nodes = treeObj.getNodesByParam("id", regionId, null);
          this.user = this.userForm.value;
          this.user.regionId = nodes[0].id;
          this.user.regionName = nodes[0].name;
          if(!!this.user.regionId){
            this.isClick = false;
          }
          this.userForm.setValue(this.user);
          this.getEnterpriseTree(regionId);
        }
      }
    );
  }

  //同步到文本框
  userUpdateZtreeClick = (even, treeId, treeNode) => {
    if(this.isClick) {
      this.clearEntAndGovTree();
      this.clearDeptTree();
      this.user = this.userForm.value;
      this.user.regionId = treeNode.id;
      this.user.regionName = treeNode.name;
      this.user.orgId = "";
      this.user.orgName = "";
      this.user.depId = "";
      this.user.depName = "";
      this.userForm.setValue(this.user);
      this.getEnterpriseTree(treeNode.id);
    }
  }

  /**
   * 获取行政区划下的政府企业
   */
  getEnterpriseTree(regionId) {
    this.usersService.getRetrieveOrganizations(regionId).subscribe(
      result => this.responseUtil.success(result, this.processEnterpriseTreeResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 对政府机构树结果处理
   * @param result
   */
  private processEnterpriseTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      //判断
      if(result.data.ENT.length != 0 || result.data.GOV.length != 0){
        // this.getUserType();
        this.governmentEntTree(result.data);
      }
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   *  政府机构树  government enterprise
   */
  private governmentEntTree(datasTree) {
    let govDatas = datasTree.GOV;
    let entDatas = datasTree.ENT;
    // 新增中的树
    let treeObj = $.fn.zTree.getZTreeObj("user_update_entAndGovTree");
    treeObj.addNodes(treeObj.getNodeByParam("id", "GOV", null), govDatas);
    treeObj.addNodes(treeObj.getNodeByParam("id", "ENT", null), entDatas);
    if(!!this.orgId){
      var nodes = treeObj.getNodesByParam("id", this.orgId, null);
      this.user = this.userForm.value;
      this.user.orgId = nodes[0].id;
      this.user.orgName = nodes[0].name;
      if(!!this.user.orgId){
        this.isOrgClick = false;
      }
      this.userForm.setValue(this.user);
      if(!!this.user.orgId){
        this.getDepartmentTree(this.orgId);
      }
    }
  }

  /**
   * 获取登录用户所属类型
   */
  private getUserType(){
    this.usersService.getCurLoginAccountInfo().subscribe(
      result => this.responseUtil.success(result, this.processUserTypeResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 处理当前登录用户组织机构信息
   * @param result
   */
  private processUserTypeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      if (!!result.data.type) {
        this.userType = result.data.type;
        this.logUtil.info('原始值：' + this.userType);
        if (this.userType == '0' || !this.userType) {
          this.userType = '00';
          this.logUtil.info('管理员以及无类型用户处理后的值：' + this.userType);
        }
      }else {
        this.userType = '00';
        this.logUtil.info('该账户未关联用户默认类型：' + this.userType);
      }
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 初始化企业、政府树的企业，政府根节点
   */
  initEnvAndGovTree() {
    let entGovSettings = {
      data: {
        keep: {
          parent: true
        }
      },
      callback: {
        onClick: this.governmentEntZtreeClick
      }
    };
    let zTreeNodes = [{name: "企业", id: "ENT"}, {name: "政府", id: "GOV"}];
    $.fn.zTree.init($("#user_update_entAndGovTree"), entGovSettings, zTreeNodes);

  }

  governmentEntZtreeClick = (even, id, treeNode) => {
    if(this.isOrgClick && treeNode.id != 'ENT' && treeNode.id != 'GOV'){
      this.clearDeptTree();

      this.user = this.userForm.value;
      this.user.orgId = treeNode.id;
      this.user.orgName = treeNode.name;
      this.user.depId = "";
      this.user.depName = "";
      this.userForm.setValue(this.user);
      if (!!treeNode.id && treeNode.id != "ENT" && treeNode.id != "GOV") {
        this.getDepartmentTree(treeNode.id);
      }
    }
  }


  clearEntAndGovTree() {
    // 新增中的树
    let treeObj = $.fn.zTree.getZTreeObj("user_update_entAndGovTree");
    treeObj.removeChildNodes(treeObj.getNodeByParam("id", "GOV", null));
    treeObj.removeChildNodes(treeObj.getNodeByParam("id", "ENT", null));
  }

  clearDeptTree() {
    $.fn.zTree.destroy("user_update_deptTree");
  }

  /**
   * 获取政府企业下的部门
   */
  getDepartmentTree(orgId) {
    this.usersService.retrieveDeptsByOrgId(orgId).subscribe(
      result => this.responseUtil.success(result, this.processDeparymentTreeResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 对部门树结果处理
   * @param result
   */
  private processDeparymentTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.departmentTree(result.data);

    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }


  /**
   *  部门树
   */
  private departmentTree(datasTree) {
    let datas = datasTree;
    // 新增中的树
    let departmentSetting = {
      callback: {
        onClick: this.departmentZtreeClick
      }
    };

   let treeObj= $.fn.zTree.init($("#user_update_deptTree"), departmentSetting, datas);

   if(!!this.depId){
     var nodes = treeObj.getNodesByParam("id", this.depId, null);
     this.user = this.userForm.value;
     this.user.depId = nodes[0].id;
     this.user.depName = nodes[0].name;
     this.userForm.setValue(this.user);
   }
  }

  /**
   * 部门回调点击事件
   * @param even
   * @param id
   * @param treeNode
   */
  departmentZtreeClick = (even, id, treeNode) => {
    this.user = this.userForm.value;
    this.user.depId = treeNode.id;
    this.user.depName = treeNode.name;
    this.userForm.setValue(this.user);
  }

  /**
   * 搜索节点，并展开
   */
  enterSearch() {
    let inputValue = $("#serach_regionName").val();
    let treeId = "user_update_orgTree";
    this.treeUtil.searchTreeNode(treeId, inputValue);
  }

  /**
   * 设置树节点字体样式
   */
  private  setFontCss_ztree(treeId, treeNode){
    if (treeNode.id == 0) {
      //根节点
      return {color: "#333", "font-weight": "bold"};
    } else if (treeNode.isParent == false) {
      //叶子节点
      return (!!treeNode.highlight) ? {color: "#48ab5d", "font-weight": "bold"} : {
          color: "#333",
          "font-weight": "normal"
        };
    } else {
      //父节点
      return (!!treeNode.highlight) ? {color: "#48ab5d", "font-weight": "bold"} : {
          color: "#333",
          "font-weight": "normal"
        };
    }
  }

}
